<template>
  <div>
    <!-- 导航栏 -->
    <van-nav-bar title="更新昵称" left-text="取消" right-text="保存" @click-left="$emit('close')" @click-right="onClickRight">
      <van-icon />
    </van-nav-bar>
    <!-- 输入框 -->
    <van-field v-model="oldName" rows="2" autosize type="textarea" maxlength="7" show-word-limit placeholder="请输入新昵称" />
  </div>
</template>

<script>
// 导入接口
import { changeUserProfile } from '@/api/user.js'
export default {
  props: {
    value: {
      type: String,
      require: true
    }
  },
  name: 'UpdateName',
  data () {
    return {
      oldName: ''
    }
  },
  methods: {
    // 保存修改名称
    async onClickRight () {
      this.$toast.loading({
        duration: 0, // 持续展示toast
        message: '修改中',
        forbidclick: 'true' // 禁止点击背景
      })
      try {
        if (this.oldName.trim() === '') return this.$toast('请输入昵称')
        await changeUserProfile({
          name: this.oldName
        })
        this.$emit('input', this.oldName)
        this.$emit('close')
        this.$toast('修改成功')
      } catch (err) {
        if (err.response?.status === 409) {
          return this.$toast('重复用户名,请更改')
        }
        this.$toast('修改失败，请重试')
      }
    }
  },
  computed: {},
  watch: {},
  filters: {},
  components: {},
  created () {
    this.oldName = this.value
  },
  mounted () { }
}
</script>

<style lang='less' scoped>
</style>
